//
//  StatusCellPictureView.swift
//  XKWeibo
//
//  Created by 小k on 15/11/14.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import SDWebImage

/// 照片之间的间距
private let StatusPictureViewItemMargin: CGFloat = 8
/// 可重用表示符号
private let StatusPictureCellId = "StatusPictureCellId"

class StatusCellPictureView: UICollectionView {
   
    /// 配图视图格子间距
    private let StatusCellPictureItemMargin: CGFloat = 8
    
    /// 微博视图模型
    var viewModle: XKStatusViewModel? {
        didSet {
            // 根据图片, 自动计算大小
            sizeToFit()
            
            // 刷新数据 － 如果不刷新，后续的 collectionView 一旦被复用，不再调用数据源方法
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateSize()
    }
    
    // MARK: - 构造函数
    init () {
        let layout = UICollectionViewFlowLayout ()
        
        // 水平 垂直 间距 都为0
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置背景颜色
        backgroundColor = UIColor(white: 0.7, alpha: 1)
        
        /// 注册可重用Cell
        registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
        
        /// 设置数据源
        dataSource = self
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - 数据源方法
extension StatusCellPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModle?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        
        cell.imageURL = viewModle?.thumbnailUrls![indexPath.item]
        
        return cell
    }
}



// MARK: - 计算视图大小
extension StatusCellPictureView {
    
    private func calculateSize () -> CGSize {
        // 1.准备
        // 每行照片数
        let rowCount: CGFloat = 3
        // 最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusCellPictureItemMargin) / rowCount - 0.001
        
        // 2.设置layout 的 itemSize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 3. 获取图片数量
        let count = viewModle?.thumbnailUrls?.count ?? 0
        
        // 开始计算
        // 1> 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        // 2> 一张图片
        if count == 1 {
            // 临时指定大小
            var size = CGSize(width: 150, height: 120)
            
            if let key = viewModle?.thumbnailUrls?.first?.absoluteString {
                
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                
                size = image.size
            }
            
            // 防止图片过窄
            size.width = size.width < 40 ? 40 : size.width
            
            // 图片过宽, 等比例缩放
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * (w / size.width)
                
                size  = CGSize(width: w, height: h)
            }
            
            // 内部图片
            layout.itemSize = size
            
            // 配图视图的大小
            return size
        }
        
        // 3> 四张图片
        if count == 4 {
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            
            return CGSize(width: w, height: w)
        }
        
        // 4> 其他图片,  九宫格计算
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let w = rowCount * itemWidth + (rowCount - 1) * StatusCellPictureItemMargin
        let h = row * itemWidth + (row - 1) * StatusCellPictureItemMargin
        
        return CGSize(width: w, height: h)
    }
}

// MARK: - 自定义配图Cell
private class StatusCellPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,
                SDWebImageOptions.RefreshCached])
        }
    }
    
    // MARK: - 重写构造函数
    override init(frame:CGRect) {
        super.init(frame: frame)
        setupUI()
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    // MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
    
    // MARK: - 设置界面
    private func setupUI () {
        // 1. 添加控件
        contentView.addSubview(iconView)
        
        // 2. 设置布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
}

